package org.jwt.servlet;

import org.jwt.entity.User;
import org.jwt.utils.JwtUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zqx
 * @date 2021-11-19
 */
@WebServlet("/api/login")
public class UserLoginServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取客户端信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 非空帐号和密码登录成功
        if(!"".equals(username) && !"".equals(password)) {
            // 定义payload信息
            Map<String,Object> payload = new HashMap<>() ;
            payload.put("username",username) ;

            // 创建Token,设置有效时间为10秒钟
            String token = JwtUtil.createToken(payload, 10*1000) ;

            // 响应客户端
            print(resp,successJson(token));
            return ;
        }
        // 登录失败
        print(resp,errorJson("错误的帐号或密码"));
    }
}
